package com.jiyi.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.TextView;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.baidu.location.Poi;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BaiduMap.OnMapStatusChangeListener;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.TextureMapView;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.swift.base.ActivityBase;
import com.swift.maintenance.R;
import com.swift.maintenance.utils.ToastUtil;

import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class Map_MyLocationActivity extends ActivityBase {

	@BindView(R.id.bmapView)
	TextureMapView mMapView;
	@BindView(R.id.tv_position)
	TextView tv_position;

	// 地图类型
	private int mapType = 0;
	private boolean isFirst = true;
	private BaiduMap mBaiduMap;
	private GeoCoder mSearch;
	private LocationClient mLocClient;
	private LatLng currentLocation;
	private String currentAddress;

	// 可接收的参数
	private String latitude;
	private String longitude;
	private String address;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_map_position);
		ButterKnife.bind(this);
		init();
	}

	private void init() {
		getIntentData();
		initTop();
		initMap();
	}

	/**
	 * @author: HYM
	 * @Title: initTop
	 * @Description: TODO(根据不同类型设置不同头部信息 1：普通定位) void
	 * @date: 2017-5-22
	 */
	private void initTop() {
		switch (mapType) {
		case 1:
			setTop("位置", "", getResources().getString(R.string.ok), false,
					true, null, null);
			break;

		default:
			break;
		}
	}

	/**
	 * @author: HYM
	 * @Title: onFinish
	 * @Description: TODO(关闭地图后的操作) void
	 * @date: 2017-5-22
	 */
	private void onFinish() {
		switch (mapType) {
		case 1:
			if (currentLocation == null) {
				ToastUtil.getInstances().showMsg("请先等待定位完成");
				return;
			}
			Intent intent = new Intent();
			intent.putExtra("latitude",
					String.valueOf(currentLocation.latitude));
			intent.putExtra("longitude",
					String.valueOf(currentLocation.longitude));
			intent.putExtra("address", currentAddress);
			setResult(RESULT_OK, intent);
			finish();
			break;

		default:
			break;
		}
	}

	/**
	 * @author: HYM
	 * @Title: getIntentData
	 * @Description: TODO(这里用一句话描述这个方法的作用) void
	 * @date: 2017-5-22
	 */
	private void getIntentData() {
		mapType = getIntent().getIntExtra("mapType", 0);
		latitude = getIntent().getStringExtra("latitude");
		longitude = getIntent().getStringExtra("longitude");
		address = getIntent().getStringExtra("address");
	}

	private void initMap() {
		// 地理经纬度反编码
		mSearch = GeoCoder.newInstance();
		mSearch.setOnGetGeoCodeResultListener(new OnGetGeoCoderResultListener() {
			@Override
			public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
				currentLocation = result.getLocation();
				currentAddress = result.getAddress();
				tv_position.setText(currentAddress);
			}

			@Override
			public void onGetGeoCodeResult(GeoCodeResult result) {
				// Toast.makeText(LocationDemo.this, result.getAddress(),
				// Toast.LENGTH_LONG).show();
			}
		});

		// 地图初始化
		mBaiduMap = mMapView.getMap();
		
		// 定位成功后地位经纬度回调监听（地图移动自带定位功能）
		mBaiduMap.setOnMapStatusChangeListener(new OnMapStatusChangeListener() {
			@Override
			public void onMapStatusChangeStart(MapStatus arg0) {
				currentLocation = null;
				tv_position.setText("定位中...");
			}

			@Override
			public void onMapStatusChangeFinish(MapStatus arg0) {
				// 回调成功后用 反Geo变成位置信息
				LatLng target = mBaiduMap.getMapStatus().target;
				LatLng ptCenter = new LatLng(target.latitude, target.longitude);
				mSearch.reverseGeoCode(new ReverseGeoCodeOption()
						.location(ptCenter));
			}

			@Override
			public void onMapStatusChange(MapStatus arg0) {

			}
		});

		// 缩放等级
		MapStatusUpdate mapStatusUpdate = MapStatusUpdateFactory.zoomBy(6);
		mBaiduMap.animateMapStatus(mapStatusUpdate);
		// 开启定位图层(蓝色边框的圆形圈圈)
		mBaiduMap.setMyLocationEnabled(true);

		// 根据接收的经纬度来判断是否定位当前位置，还是根据接收的经纬度定位位置
		if (!TextUtils.isEmpty(latitude) && !TextUtils.isEmpty(longitude)) {
			// 定位当前位置并做标记
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(300F)
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(Double.parseDouble(latitude))
					.longitude(Double.parseDouble(longitude)).build();
			mBaiduMap.setMyLocationData(locData);

			// 移动到定位位置
			LatLng ll = new LatLng(Double.parseDouble(latitude),Double.parseDouble(longitude));
			currentLocation = ll;
			MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
			mBaiduMap.animateMapStatus(u);
			tv_position.setText(address);
		} else {
			// 开启定位当前位置
			mMapView.postDelayed(new Runnable() {
				@Override
				public void run() {
					// 定位初始化
					mLocClient = new LocationClient(Map_MyLocationActivity.this);
					mLocClient
							.registerLocationListener(new MyLocationListenner());
					LocationClientOption option = new LocationClientOption();
					option.setOpenGps(true); // 打开gps
					option.setCoorType("bd09ll"); // 设置坐标类型
//					option.setIsNeedLocationDescribe(true);//可选，默认false，设置是否需要位置语义化结果，可以在BDLocation.getLocationDescribe里得到，结果类似于“在北京天安门附近”
					option.setIsNeedLocationPoiList(true);//可选，默认false，设置是否需要POI结果，可以在BDLocation.getPoiList里得到
					mLocClient.setLocOption(option);
					mLocClient.start();
				}
			}, 500);
		}

	}

	/**
	 * 定位SDK监听函数
	 */
	public class MyLocationListenner implements BDLocationListener {
		@Override
		public void onReceiveLocation(BDLocation location) {
			// map view 销毁后不在处理新接收的位置
			if (location == null || mMapView == null)
				return;
			 List<Poi> list = location.getPoiList();    // POI数据
		        if (list != null) {
		            for (Poi p : list) {
		                
		            }
		        }
			// 定位当前位置并做标记
			MyLocationData locData = new MyLocationData.Builder()
					.accuracy(location.getRadius())
					// 此处设置开发者获取到的方向信息，顺时针0-360
					.direction(100).latitude(location.getLatitude())
					.longitude(location.getLongitude()).build();
			mBaiduMap.setMyLocationData(locData);

			// 移动到定位位置
			if (isFirst) {
				isFirst = false;
				LatLng ll = new LatLng(location.getLatitude(),
						location.getLongitude());
				MapStatusUpdate u = MapStatusUpdateFactory.newLatLng(ll);
				// 地图移动会调用反编码
				mBaiduMap.animateMapStatus(u);
			}
		}

		public void onReceivePoi(BDLocation poiLocation) {
		}

	}

	@Override
	protected void onPause() {
		mMapView.onPause();
		super.onPause();
	}

	@Override
	protected void onResume() {
		mMapView.onResume();
		super.onResume();
	}

	@Override
	protected void onDestroy() {
		// 退出时销毁定位
		if (mLocClient != null && mLocClient.isStarted()) {
			mLocClient.stop();
		}

		// 关闭定位图层
		mBaiduMap.setMyLocationEnabled(false);
		mMapView.onDestroy();
		mMapView = null;
		super.onDestroy();
	}

	@OnClick({ R.id.tvTitle, R.id.tvSearch })
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.tvTitle:
			finish();
			break;
		case R.id.tvSearch:
			// 完成定位
			onFinish();
			break;
		default:
			break;
		}
	}
}
